package com.qezhhnjy.demo.netty.client;

import com.qezhhnjy.demo.netty.handler.MyChannelHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyangfu
 * @date 2021/6/18-15:19
 */
@Slf4j
public class FirstClient {

    public static void start() throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();

        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .remoteAddress("localhost", 8888)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new MyChannelHandler());
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                }
            });

        Channel channel = bootstrap.connect().sync().channel();
        channel.eventLoop().scheduleAtFixedRate(() -> channel.writeAndFlush(Unpooled.copyLong(new Date().getTime())), 1, 1, TimeUnit.SECONDS);
    }
}
